const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const indexRouter = require('./routes/index');
const usersRouter = require('./routes/users');
const bodyParser = require('body-parser');
const WebSocket = require('ws');
const app = express();

// 视图引擎设置
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// 中间件设置
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
// app.use('/react', express.static('public/react-build'));
app.use(express.static(path.join(__dirname, 'public')));


// 添加跨域支持
app.options('/upload', (req, res) => {
  res.header('Access-Control-Allow-Methods', 'POST, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type, x-device-id');
  res.status(200).send();
});

// 存储所有连接的客户端
const clients = new Set();

app.use(bodyParser.raw({
  type: 'image/jpeg',
  limit: '10mb'
}));

// 路由
app.use('/', indexRouter);
app.use('/users', usersRouter);



// 广播图像给所有客户端
function broadcastImage(imageData, deviceId) {
  clients.forEach(client => {
    if (client.readyState === WebSocket.OPEN) {
      try {
        client.send(imageData);
      } catch (e) {
        console.error('Error sending to WebSocket client:', e.message);
      }
    }
  });
}

app.get('/test', (req, res) => {
  res.send('测试接口1');
});

// 接收来自 ESP32 的图像
app.post('/upload', (req, res) => {
  console.log('Received frame from ESP32');
  const imageData = req.body;  // 现在可以正确获取二进制数据

  if (!imageData || imageData.length === 0) {
    return res.status(400).send('Empty frame');
  };

  const deviceId = req.headers['x-device-id'] || 'unknown';
  console.log(`Received frame from device: ${deviceId}, size: ${imageData.length} bytes`);

  // 广播给所有 WebSocket 客户端
  broadcastImage(imageData, deviceId);

  res.status(200).send('Image received');
});
// 创建 WebSocket 服务器
const wss = new WebSocket.Server({ port: 8088 });
wss.on('connection', (ws) => {
  clients.add(ws);
  console.log('New WebSocket client connected');

  ws.on('close', () => {
    clients.delete(ws);
    console.log('WebSocket client disconnected');
  });

  ws.on('error', (err) => {
    console.error('WebSocket error:', err.message);
  });
});


// 错误处理器
app.use(function (err, req, res, next) {
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  res.status(err.status || 500);
  res.render('error');
});

// 404 处理器 (放在最后)
app.use(function (req, res, next) {
  console.log(`404: ${req.method} ${req.path}`);
  next(createError(404));
});




module.exports = app;